import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {TicketRecordListItem, TicketRecordList, UserIdentity} from 'src/utils/server.interface'
import {AtCheckbox, AtActionSheetItem, AtActionSheet, AtListItem, AtList} from 'taro-ui'
import {View, Text, Picker, Image} from '@tarojs/components'
import {user} from '../../utils/user.service'
import {http} from '../../utils/http'
import {vcmonitor} from "../../utils/tools";
import {
  STATISTIC_GOODS_LIST_NEW,
  STATISTIC_GOODS_LIST_BY_SELLER_NEW,
  STATISTIC_GOODS_LIST_BY_STORE,
  RESOURCE_URL,
  IDENTITY,
  TARO_ENV
} from '../../constants/api'
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Index from "../components/water-mark/index";
import './ticket-summary.scss'

export default class TicketSummary extends Component {
  state: {
    supplierChecked: string
    supplierList: any
    checkboxOption: any
    tableData: any
    startDate: string
    endDate: string
    supplierIndex: number
    recordList: TicketRecordList
    ticketList: TicketRecordListItem[]
    inputText: string
    showSearch: boolean
    loadMoreStatus: "more" | "loading" | "noMore"
  } = {
    ticketList: [],
    showSearch: false,
    checkboxOption: [{
      value: 'showTimePeriod',
      label: '显示时段票',
      desc: ''
    }],
    tableData: [],
    startDate: '',
    endDate: '',
    recordList: {
      firstPage: true,
      lastPage: false,
      pageNumber: 1,
      pageSize: 10,
      supplierChecked: '',
      inputText: '',
      checkMsg: '',
      supplierIndex: 0,
      totalPage: 1,
      totalRow: 0,
      list: []
    },
    loadMoreStatus: 'loading',
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (TARO_ENV === 'weapp') {
      Taro.hideShareMenu()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    }
    const userIdentity = await http.get<UserIdentity>(IDENTITY, {})
    if (userIdentity && userIdentity.isSupplier) {
      const that = this
      let supplierChecked = ''
      let supplierIndex = Taro.getStorageSync('supplierIndex') || 0
      if (userIdentity.SupplierList.length > 0) {
        supplierIndex = userIdentity.SupplierList.length < supplierIndex ? userIdentity.SupplierList.length - 1 : supplierIndex
        supplierChecked = userIdentity.SupplierList[supplierIndex].company
        this.supplierId = userIdentity.SupplierList[supplierIndex].supplier_id
        Taro.setStorageSync('supplierIndex', supplierIndex)
      }
      this.setState({supplierList: userIdentity.SupplierList, supplierChecked, supplierIndex}, async () => {
        this.getData()
      })
    }
  }

  page = 1
  supplierId = 0

  inputChange(value) {
    this.setState({inputText: value.detail.value})
  }

  async getData() {
    await Taro.showLoading({title: '加载中...'})
    let startDate = this.state.startDate
    let endDate = this.state.endDate
    let apiPath = STATISTIC_GOODS_LIST_NEW;
    if (process.env.TARO_ENV === 'h5' && startDate && endDate) {
      const date1 = new Date(startDate)
      const date2 = new Date(endDate)
      const y = date1.getFullYear() + '-'
      const m = (date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1) + '-'
      const d = (date1.getDate() < 10 ? '0' + date1.getDate() : date1.getDate())
      const y2 = date2.getFullYear() + '-'
      const m2 = (date2.getMonth() + 1 < 10 ? '0' + (date2.getMonth() + 1) : date2.getMonth() + 1) + '-'
      const d2 = (date2.getDate() < 10 ? '0' + date2.getDate() : date2.getDate())
      startDate = y + m + d
      endDate = y2 + m2 + d2
    }
    if(this.type === 'goods') {
      apiPath = STATISTIC_GOODS_LIST_NEW;
    }else if(this.type === 'channel') {
      apiPath = STATISTIC_GOODS_LIST_BY_SELLER_NEW;
    }else {
      apiPath = STATISTIC_GOODS_LIST_BY_STORE;
    }
    const data = await http.carGet(apiPath, {
      startDate,
      endDate,
      supplier_id: this.supplierId
    })
    console.log("data : ", data);
    let resultData = {};
    if(Object.keys(data).length === 0) {
      resultData.data = [];
      resultData.total_num = 0;
    }else {
      resultData = data;
    }
    this.setState({tableData: resultData})
    Taro.hideLoading()
  }

  onChange(e) {
    const {supplierList} = this.state
    const supplierIndex = Number(e.detail.value)
    const supplierChecked = supplierList[supplierIndex].company
    this.setState({supplierIndex, supplierChecked}, () => {
      Taro.setStorageSync('supplierIndex', supplierIndex)
      this.getData()
      this.supplierId = supplierList[supplierIndex].supplier_id
    })
  }

  handleChange(value) {
    this.setState({
      checkedList: value
    })
  }

  handleClick(value) {
    this.type = value
    this.getData()
    this.setState({showSearch: false})
  }

  onDateChange(value, e) {
    const val = e.detail.value
    if (value === 'startDate') {
      this.setState({startDate: val}, async () => {
        if (this.state.startDate && this.state.endDate) {
          this.getData()
        }
      })
    } else {
      this.setState({endDate: val}, async () => {
        if (this.state.startDate && this.state.endDate) {
          this.getData()
        }
      })
    }

  }

  type = 'goods'

  render() {
    const {startDate, endDate, tableData, showSearch, checkboxOption, checkedList, supplierList, supplierChecked, supplierIndex} = this.state
    return (
      <View className='check-ticket-root'>
        <GzhAuth />
        <Index />
        <View className="summary-head">
          {!!supplierList && supplierList.length > 1 &&<View className='head-bg'>
            <View className='header-bar'>
              <View className='head-picker'>
                {!!supplierList && supplierList.length > 1 &&
                <Picker value={supplierIndex} range={supplierList} rangeKey='company' onChange={this.onChange.bind(this)}>
                  <View className={supplierChecked ? 'picker' : 'picker off'}>
                    {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                    <Text>切换</Text>
                  </View>
                </Picker>}
              </View>
            </View>
          </View>}
          <View className='header-time'>
            <Picker mode='date' className='startDate' onChange={this.onDateChange.bind(this, 'startDate')}>
              <AtList>
                <AtListItem title={startDate ? '' : '请选择日期'} extraText={startDate} />
              </AtList>
            </Picker> 至 <Picker className='endDate' mode='date' onChange={this.onDateChange.bind(this, 'endDate')}>
            <AtList>
              <AtListItem title={endDate ? '' : '请选择日期'} extraText={endDate} />
            </AtList>
          </Picker>
          </View>
          <View className='search-area'>
            {
              tableData.is_show_booktime &&
              <AtCheckbox
                options={checkboxOption}
                selectedList={checkedList}
                onChange={this.handleChange.bind(this)}
              />
            }
            <Image className='main-bg' onClick={() => {
              this.setState({showSearch: true});
            }} src={RESOURCE_URL + "/upload/images/20210423/1619148481692_360.png"}
            />
            <AtActionSheet isOpened={showSearch}>
              <AtActionSheetItem onClick={this.handleClick.bind(this, 'goods')}>
                按商品
              </AtActionSheetItem>
              <AtActionSheetItem onClick={this.handleClick.bind(this, 'channel')}>
                按渠道
              </AtActionSheetItem>
              {
                process.env.P_ENV === 'kd' &&
                <AtActionSheetItem onClick={this.handleClick.bind(this, 'store')}>
                  按门店
                </AtActionSheetItem>
              }
            </AtActionSheet>
          </View>
        </View>
        <View className='content'>
          {tableData && tableData.data && tableData.data.length > 0 && tableData.data.map((item, index) => <View key={index}
            className='card'
          >
            {this.type === 'goods' && <View className='content-item'>
              <View className='title-once'>{item.alias ? item.alias : item.name}</View>
              <View className='intotal'>合计 : <Text className='num-card'>{item.used_check_num}张</Text></View>
            </View>}

            {this.type === 'store' && <View className='content-item'>
              <View className='title-once'>{item.name}</View>
              <View className='intotal'>合计 : <Text className='num-card'>{item.check_num}张</Text></View>
            </View>}

            {this.type === 'channel' && <View className='content-items-channel'>
              <View className='channel-name'>{item.seller_name}</View>
              {item.data && item.data.map((items, idx) =>
                <View key={idx}>
                  <View className='content-item'>
                    <View className='title-once'>{items.product_name}</View>
                    <View className='intotal'>合计 : <Text className='num-card'>{items.pTotal_num}张</Text></View>
                  </View>
                  <View className='content-items'>
                    {items.data && items.data.length > 0 && items.data.map((itemss, indexs) =>
                      <View className='wrapper' key={indexs}>
                        <View className='content-itemsss'>
                          <View className='title-title'>{itemss.name}</View>
                          <View className='num-card-num-card'>{itemss.used_check_num}张</View>
                        </View>
                      </View>)
                    }
                  </View>
                </View>
              )}
              <View className='channel-intotal'>合计 : <Text
                className='num-card'
              >{item.sTotal_num}张</Text></View>
            </View>}
          </View>)}
          {
            !!tableData.data && tableData.data.length <= 0 && <View className='nomore'>没有更多了</View>
          }
          <View className='total-num'>共计 : <Text className='card-num-total'>{tableData.total_num}张</Text></View>
        </View>
      </View>
    )
  }
}
